/**
 * Created by w on 2014/11/26.
 */
if (document.addEventListener) {
    document.addEventListener("DOMContentLoaded", function () {
        window.dice = new DICE();
        document.querySelector('#start').addEventListener("click", function () {
            dice.run();
        }, false);
    }, false);
}

var DICE = function () {
    this.init()
};
DICE.prototype.init = function () {
    this.el = document.querySelector('#canvas');
    this.result = document.querySelector('#result');
    this.ctx = this.el.getContext('2d');
    this.width = this.el.width;
    this.height = this.el.height;
    this.diceWidth = this.diceHeight = 100;
    this.sum = 0;
    this.reset = true;
    this.dicePos = [{x: 66, y: 100}, {x: 232, y: 100}];
    this.numDotPos = [[], [5], [4, 6], [1, 5, 9], [1, 3, 7, 9], [1, 3, 5, 7, 9], [1, 3, 4, 6, 7, 9]];
    this.dotPos = [{}];
    for (var i = 1; i < 4; i++) {
        for (var j = 1; j < 4; j++) {
            this.dotPos.push({x: j * 25, y: i * 25});
        }
    }
    return this;
};
DICE.prototype.run = function () {
    return this.drawTWO();
};
DICE.prototype.drawTWO = function () {
    var sum = 0, num;
    for (var i = 0; i < 2; i++) {
        num = 1 + Math.floor(Math.random() * 6);
        this.drawDICE(num, this.dicePos[i]);
        sum += num;
    }
    console.log("sum=" + sum);
    if (this.reset) {
        if ([7, 11].indexOf(sum) > -1) {
            this.result.innerHTML = 'You win!';
            this.result.classList.add("win");
            this.result.classList.remove("lost");
        } else if ([2, 3, 12].indexOf(sum) > -1) {
            this.result.innerHTML = 'You lost!';
            this.result.classList.add("lost");
            this.result.classList.remove("win");
        } else {
            this.sum = sum;
            this.result.innerHTML = 'Please continue!';
            this.result.classList.remove("win");
            this.result.classList.remove("lost");
            this.reset = false;
        }
    } else {
        if (sum == 7) {
            this.result.innerHTML = 'You lost!';
            this.result.classList.add("lost");
            this.result.classList.remove("win");
        } else if (sum == this.sum) {
            this.result.innerHTML = 'You win!';
            this.result.classList.add("win");
            this.result.classList.remove("lost");
        }
        this.reset = true;
    }
    return this;
};
DICE.prototype.drawDICE = function (num, p) {
    var posArr = this.numDotPos[num], pos;
    this.ctx.lineWidth = 5;
    this.ctx.clearRect(p.x, p.y, this.diceWidth, this.diceHeight);
    this.ctx.strokeRect(p.x, p.y, this.diceWidth, this.diceHeight);
    this.ctx.fillStyle = '#009966';
    for (var i = 0, j = posArr.length; i < j; i++) {
        pos = this.dotPos[posArr[i]];
        this.ctx.beginPath();
        this.ctx.arc(p.x + pos.x, p.y + pos.y, 12, 0, Math.PI * 2, true);
        this.ctx.closePath();
        this.ctx.fill();
    }
    return this;
};